package org.peppa.utils;

import com.fazecast.jSerialComm.SerialPort;

import java.util.ArrayList;
import java.util.List;

public class ModeBusCommunicationUtil {

    public static List<String> getCurrentSysPortName() {
        List<String> portName = new ArrayList<String>();
        for (SerialPort commPort : SerialPort.getCommPorts()) {
            portName.add(commPort.getSystemPortName());
        }
        return portName;
    }

    public static SerialPort openPort(String portName)  {
        SerialPort serialPort = SerialPort.getCommPort(portName);
        if (serialPort.openPort()) new Exception("No such port");
        serialPort.setComPortParameters(115200, 8, SerialPort.ONE_STOP_BIT, SerialPort.NO_PARITY);
//        serialPort.setComPortParameters(baudRate, dataBits, stopBits, parity);
        serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 0, 0);
        return serialPort;
    }

    public static void sendMessage(SerialPort serialPort, byte[] writeBuffer) {
//        byte[] data = new byte[writeBuffer.length];
//        for (int i = 0; i < writeBuffer.length; i++) {
//            data[i] = (byte) writeBuffer[i];
//        }
        serialPort.writeBytes(writeBuffer, writeBuffer.length);
    }

    public static void closePort(SerialPort serialPort) {
        serialPort.closePort();
    }

    public static void readPort(SerialPort serialPort) {
        if (serialPort.isOpen()) {
            byte[] readBuffer = new byte[1024];
            Thread readThread = new Thread(() -> {
                while (true) {
                    int numRead = serialPort.readBytes(readBuffer, readBuffer.length);
                    if (numRead > 0) {
                        String receivedData = new String(readBuffer, 0, numRead);
                        System.out.println("Received: " + receivedData);
                    }
                }
            });
            readThread.start();
        }
    }
}
